﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    ViewData["Title"] = "来料检验管理";
    Layout = null;
}

@Html.AntiForgeryToken()

<!-- 先加载CSS -->
<link href="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/css/layui.min.css" rel="stylesheet">

<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-header">
            <h3>来料检验管理</h3>
        </div>
        <div class="layui-card-body">
            <form class="layui-form" id="searchForm">
                <div class="layui-form-item">
                    <div class="layui-inline">
                        <label class="layui-form-label">检验单编号</label>
                        <div class="layui-input-inline">
                            <input type="text" name="incomingInspectionCode" placeholder="请输入检验单编号" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">供应商批次号</label>
                        <div class="layui-input-inline">
                            <input type="text" name="batch" placeholder="请输入供应商批次号" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">检测结果</label>
                        <div class="layui-input-inline">
                            <select name="testingResult">
                                <option value="">全部</option>
                                <option value="通过">通过</option>
                                <option value="未通过">未通过</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">检测人员</label>
                        <div class="layui-input-inline">
                            <input type="text" name="testingPerson" placeholder="请输入检测人员" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">产品物料名称</label>
                        <div class="layui-input-inline">
                            <input type="text" name="productName" placeholder="请输入产品物料名称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">来料日期</label>
                        <div class="layui-input-inline">
                            <input type="date" name="incomingDate" class="layui-input" />
                        </div>
                    </div>
                    <div class="layui-inline">
                        <label class="layui-form-label">检测日期</label>
                        <div class="layui-input-inline">
                            <input type="date" name="testingDate" class="layui-input" />
                        </div>
                    </div>
                    <div class="layui-inline">
                        <button type="submit" class="layui-btn" lay-submit lay-filter="searchForm">
                            <i class="layui-icon layui-icon-search"></i> 搜索
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>

            <div class="layui-btn-group">
                <button class="layui-btn" id="addBtn">
                    <i class="layui-icon layui-icon-add-1"></i> 新增
                </button>
                <button class="layui-btn layui-btn-danger" id="batchDeleteBtn">
                    <i class="layui-icon layui-icon-delete"></i> 批量删除
                </button>
                <button class="layui-btn layui-btn-normal" id="exportBtn">
                    <i class="layui-icon layui-icon-export"></i> 导出Excel
                </button>
            </div>

            <table id="mainTable" lay-filter="mainTable"></table>
        </div>
    </div>
</div>

<!-- 弹窗表单模板 -->
<script type="text/html" id="formTpl">
    <form class="layui-form" lay-filter="mainForm" style="margin: 20px;">
        <input type="hidden" name="Id">
        <div class="layui-form-item">
            <label class="layui-form-label required">检验单编号</label>
            <div class="layui-input-inline" style="width: 250px;">
                <input type="text" name="IncomingInspectionCode" required lay-verify="required" placeholder="请输入检验单编号" autocomplete="off" class="layui-input">
            </div>
            <input type="checkbox" lay-skin="switch" lay-filter="autoGenInspectionCodeSwitch" lay-text="自动生成|手动输入" id="autoGenInspectionCodeSwitch" checked>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label required">检验单名称</label>
            <div class="layui-input-block">
                <input type="text" name="IncomingInspectionName" required lay-verify="required" placeholder="请输入检验单名称" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">供应商简称</label>
            <div class="layui-input-block">
                <input type="text" name="IncomingInspectionJName" placeholder="请输入供应商简称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">供应商批次号</label>
            <div class="layui-input-block">
                <input type="text" name="Batch" placeholder="请输入供应商批次号" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">产品物料编号</label>
            <div class="layui-input-block">
                <input type="text" name="ProductCode" placeholder="请输入产品物料编号" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">产品物料名称</label>
            <div class="layui-input-block">
                <input type="text" name="ProductName" placeholder="请输入产品物料名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">接收数量</label>
            <div class="layui-input-block">
                <input type="number" name="ReceiveNum" placeholder="请输入接收数量" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">检测数量</label>
            <div class="layui-input-block">
                <input type="number" name="TestingNum" placeholder="请输入检测数量" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">不合格数</label>
            <div class="layui-input-block">
                <input type="number" name="UnqualifiedNum" placeholder="请输入不合格数" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">检测结果</label>
            <div class="layui-input-block">
                <select name="TestingResult">
                    <option value="">请选择</option>
                    <option value="通过">通过</option>
                    <option value="未通过">未通过</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">来料日期</label>
            <div class="layui-input-block">
                <input type="date" name="IncomingDate" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">检测日期</label>
            <div class="layui-input-block">
                <input type="date" name="TestingDate" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">检测人员</label>
            <div class="layui-input-block">
                <input type="text" name="TestingPerson" placeholder="请输入检测人员" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">单据状态</label>
            <div class="layui-input-block">
                <select name="State">
                    <option value="0">已确定</option>
                    <option value="1">已取消</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="submitForm">提交</button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>
</script>

<!-- 先加载jQuery，再加载Layui -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdn.bootcdn.net/ajax/libs/layui/2.6.8/layui.min.js"></script>

<script>
    layui.use(['table', 'form', 'layer'], function(){
        var table = layui.table;
        var form = layui.form;
        var layer = layui.layer;
        var $ = layui.$;

        // 初始化表格
        function loadTable(params) {
            var searchParams = params || {};
            searchParams.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();

            table.render({
                elem: '#mainTable',
                url: '/IncomingInspection/GetIncomingInspectionList',
                method: 'get',
                where: searchParams,
                page: true,
                limit: 10,
                cols: [[
                    {type: 'checkbox'},
                    {field: 'id', title: 'ID', width: 80},
                    {field: 'incomingInspectionCode', title: '检验单编号', width: 120},
                    {field: 'incomingInspectionName', title: '检验单名称', width: 120},
                    {field: 'incomingInspectionJName', title: '供应商简称', width: 120},
                    {field: 'batch', title: '供应商批次号', width: 120},
                    {field: 'productCode', title: '产品物料编号', width: 120},
                    {field: 'productName', title: '产品物料名称', width: 120},
                    {field: 'receiveNum', title: '接收数量', width: 100},
                    {field: 'testingNum', title: '检测数量', width: 100},
                    {field: 'unqualifiedNum', title: '不合格数', width: 100},
                    {field: 'testingResult', title: '检测结果', width: 100},
                    {field: 'incomingDate', title: '来料日期', width: 110, templet: d => d.incomingDate ? d.incomingDate.split('T')[0] : '' },
                    {field: 'testingDate', title: '检测日期', width: 110, templet: d => d.testingDate ? d.testingDate.split('T')[0] : '' },
                    {field: 'testingPerson', title: '检测人员', width: 100},
                    {field: 'state', title: '单据状态', width: 90, templet: d => d.state === 0 ? '已确定' : '已取消'},
                    {fixed: 'right', title: '操作', toolbar: '#tableBar', width: 120}
                ]],
                response: {
                    statusCode: 0
                },
                parseData: function(res) {
                    return {
                        "code": 0,
                        "msg": res.msg,
                        "count": res.count || res.totalCount || 0,
                        "data": res.data || res.items || []
                    };
                }
            });
        }

        // 加载初始数据
        loadTable();

        // 搜索按钮点击事件
        form.on('submit(searchForm)', function(data){
            loadTable(data.field);
            return false;
        });

        // 批量删除按钮点击事件
        $('#batchDeleteBtn').on('click', function(){
            var checkStatus = table.checkStatus('mainTable');
            var data = checkStatus.data;
            if(data.length === 0){
                layer.msg('请选择要删除的记录');
                return;
            }
            layer.confirm('确定要删除选中的'+data.length+'条记录吗？', function(index){
                var ids = data.map(function(item){ return item.id; });
                $.ajax({
                    url: '/IncomingInspection/BatchDelete',
                    type: 'POST',
                    data: {
                        ids: ids,
                        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                    },
                    headers: {
                        'RequestVerificationToken': $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function(res){
                        if(res.code === 0){
                            layer.msg(res.msg);
                            table.reload('mainTable');
                        } else {
                            layer.msg(res.msg);
                        }
                    },
                    error: function(xhr){
                        layer.msg(xhr.responseJSON?.msg || '操作失败，请重试');
                    }
                });
                layer.close(index);
            });
        });

        // 导出按钮点击事件
        $('#exportBtn').on('click', function(){
            var searchParams = form.val('searchForm');
            var queryString = Object.keys(searchParams)
                .filter(key => searchParams[key])
                .map(key => key + '=' + encodeURIComponent(searchParams[key]))
                .join('&');
            window.location.href = '/IncomingInspection/ExportExcel?' + queryString;
        });

        // 添加按钮点击事件
        $('#addBtn').on('click', function(){
            openForm();
        });

        // 打开表单
        function openForm(data) {
            var title = data ? '编辑来料检验' : '添加来料检验';
            layer.open({
                type: 1,
                title: title,
                area: ['600px', '90%'],
                content: $('#formTpl').html(),
                success: function(layero, index){
                    form.render(null, 'mainForm');

                    if(data){
                        form.val('mainForm', {
                            "Id": data.id,
                            "IncomingInspectionCode": data.incomingInspectionCode,
                            "IncomingInspectionName": data.incomingInspectionName,
                            "IncomingInspectionJName": data.incomingInspectionJName,
                            "Batch": data.batch,
                            "ProductCode": data.productCode,
                            "ProductName": data.productName,
                            "ReceiveNum": data.receiveNum,
                            "TestingNum": data.testingNum,
                            "UnqualifiedNum": data.unqualifiedNum,
                            "TestingResult": data.testingResult,
                            "IncomingDate": data.incomingDate ? data.incomingDate.split('T')[0] : '',
                            "TestingDate": data.testingDate ? data.testingDate.split('T')[0] : '',
                            "TestingPerson": data.testingPerson,
                            "State": data.state
                        });
                    }

                    // 默认自动生成编号并只读
                    $.get('/IncomingInspection/GenerateInspectionCode', function(res) {
                        if(res.code === 0 && res.inspectionCode){
                            layero.find('input[name="IncomingInspectionCode"]').val(res.inspectionCode).prop('readonly', true);
                        }
                    });

                    // 监听开关切换
                    form.on('switch(autoGenInspectionCodeSwitch)', function(data){
                        if(data.elem.checked){
                            // 自动生成
                            $.get('/IncomingInspection/GenerateInspectionCode', function(res) {
                                if(res.code === 0 && res.inspectionCode){
                                    layero.find('input[name="IncomingInspectionCode"]').val(res.inspectionCode).prop('readonly', true);
                                }
                            });
                        }else{
                            // 手动输入
                            layero.find('input[name="IncomingInspectionCode"]').val('').prop('readonly', false);
                        }
                    });

                    // 监听提交
                    form.on('submit(submitForm)', function(formData){
                        var isEdit = data ? true : false;
                        var url = isEdit ? '/IncomingInspection/Update' : '/IncomingInspection/AddIncomingInspection';
                        var postData = formData.field;
                        postData.__RequestVerificationToken = $('input[name="__RequestVerificationToken"]').val();
                        $.ajax({
                            url: url,
                            type: 'POST',
                            data: postData,
                            success: function(res){
                                if(res.code === 0){
                                    layer.close(index);
                                    layer.msg(title + '成功');
                                    table.reload('mainTable');
                                } else {
                                    layer.msg(res.msg || (title + '失败'));
                                }
                            },
                            error: function(xhr){
                                layer.msg(xhr.responseJSON?.msg || '操作失败，请重试');
                            }
                        });
                        return false;
                    });

                    layero.find('input[name="IncomingInspectionCode"]').on('blur', function() {
                        var code = $(this).val();
                        if(!code) return;
                        $.get('/IncomingInspection/CheckInspectionCodeExists', { inspectionCode: code }, function(res) {
                            if(res.code === 0 && res.exists){
                                layer.msg('检验单编号已存在，请重新输入', {icon: 2});
                                layero.find('input[name="IncomingInspectionCode"]').focus();
                            }
                        });
                    });
                }
            });
        }

        // 监听工具条
        table.on('tool(mainTable)', function(obj){
            var data = obj.data;
            if(obj.event === 'edit'){
                openForm(data);
            } else if(obj.event === 'del'){
                layer.confirm('确定要删除此记录吗？', function(index){
                    $.ajax({
                        url: '/IncomingInspection/Delete',
                        type: 'POST',
                        data: {
                            id: data.id,
                            __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                        },
                        success: function(res){
                            if(res.code === 0){
                                obj.del();
                                layer.msg('删除成功');
                            } else {
                                layer.msg(res.msg || '删除失败');
                            }
                        },
                        error: function(xhr){
                            layer.msg(xhr.responseJSON?.msg || '删除失败，请重试');
                        }
                    });
                    layer.close(index);
                });
            }
        });
    });
</script>

<!-- 工具条模板 -->
<script type="text/html" id="tableBar">
    <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

<style>
    .layui-form-label.required:after {
        content: '*';
        color: red;
        margin-left: 4px;
    }

    .layui-card {
        margin: 15px;
    }

    .layui-form-item {
        margin-bottom: 15px;
    }
</style>
